package com.example.controller;

import com.example.cache.TagCache;
import com.example.exception.CustomizeErrorCode;
import com.example.exception.CustomizeException;
import com.example.mapper.NoticeMapper;
import com.example.model.LoginUser;
import com.example.model.Notice;
import com.example.model.Question;
import com.example.service.impl.PublishService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Date;
import java.util.Set;

/**
 * Author by admin, Email xx@xx.com, Date on 2019/8/4.
 * PS: Not easy to write code, please indicate.
 */
@Controller
public class publishController {
    @Autowired
    PublishService publishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private NoticeMapper noticeMapper;


    @GetMapping("/publish")
    public String publish(Model model)
    {
        model.addAttribute("tags", TagCache.get());
        return "publish";
    }

    @GetMapping("/publish/{id}")
    public  String edit(@PathVariable(name = "id")Integer id,Model model){
        Question question = publishService.getquetionByid(id);
        model.addAttribute("title",question.getTitle());
        model.addAttribute("description",question.getDescription());
        model.addAttribute("tag",question.getTag());
        model.addAttribute("tags", TagCache.get());
        return "publish";
    }
    @PostMapping("/publish")
    public String doPublish(Question questionvo,Model model) {
        model.addAttribute("title", questionvo.getTitle());
        model.addAttribute("description", questionvo.getDescription());
        model.addAttribute("tag", questionvo.getTag());
        model.addAttribute("tags", TagCache.get());
        if (questionvo.getTitle() == null || questionvo.getTitle() == "") {
            model.addAttribute("error", "标题不能为空");
            return "PublishService";
        }
        if (questionvo.getDescription() == null || questionvo.getDescription() == "") {
            model.addAttribute("error", "问题补充不能为空");
            return "PublishService";
        }
        if (questionvo.getTag() == null || questionvo.getTag() == "") {
            model.addAttribute("error", "标签不能为空");
            return "PublishService";
        }
        String invalid = TagCache.filterInvalid(questionvo.getTag());
        if (StringUtils.isNotBlank(invalid)) {
            model.addAttribute("error", "输入非法标签:" + invalid);
            return "publish";
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if("anonymousUser" == authentication.getPrincipal()){
            model.addAttribute("error", "用户未登录");
            return "publish";
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //通过jwt 拿到userId
        Long userId = loginUser.getUser().getId();
        String accountId = loginUser.getUser().getAccountId();
        if (questionvo.getId()==null)
            {
                Question question = new Question();
                question.setTitle(questionvo.getTitle());
                question.setDescription(questionvo.getDescription());
                question.setTag(questionvo.getTag());
                question.setCreator(userId);
                question.setGmtCreate(new Date());
                question.setThumbup(0);
                question.setCommentCount(0);
                question.setViewCount(0);
                question.setLikeCount(0);
                publishService.save(question);
                //保存通知消息
                String authorKey = "article_author_"+userId;
                //拿到redis中作者1的所有订阅者信息。
                Set<String> set = redisTemplate.boundSetOps(authorKey).members();
                if (null!=set && set.size()>0){
                    //给订阅者发送消息
                    Notice notice =null;
                    for (String uid : set) {
                        notice = new Notice();
                        //接收消息的用户ID
                        notice.setReceiverId(Integer.valueOf(uid));
                        //进行操作用户的ID
                        notice.setOperatorId(userId.intValue());
                        //被操作的类型
                        notice.setAction("publish");
                        //被操作的对象。
                        notice.setTargetType("article");
                        //被操作文章的ID
                        notice.setTargetId(question.getId().intValue());
                        notice.setCreatetime(new Date());
                        //通知类型
                        notice.setType("sys");
                        notice.setState(0);
                        //保存消息
                        noticeMapper.insert(notice);

                        //发消息rabbitmq，新消息通知，订阅消息 （交换机，路由键,消息内容）
                        rabbitTemplate.convertAndSend("article_subscribe",userId.toString(),
                                "您关注的作者:"+accountId+",发布新文章《"+question.getTitle()+"》");
                    }
                }
            }
        //存在就修改
        else {
           if(!publishService.updateQuestion(questionvo)){
               throw  new CustomizeException(CustomizeErrorCode.QUESTION_NOT_FOUND);
           }
        }
        return "redirect:/";
    }
}
